/*
 * @Descripttion: 
 * @version: 
 * @Author: hzj-1510017964@qq.com
 * @Date: 2020-04-22 12:57:40
 * @LastEditors: hzj-1510017964@qq.com
 * @LastEditTime: 2020-05-07 10:11:16
 */

const jwt = require('jsonwebtoken')
const app = require('../config/appConfig')
const redisDb = require('../config/redisConfig')
const httpResult = require('../utils/httpResult')


//系统异常处理
const errorSystem = async (ctx, next) => {
    try {
        await next()
    } catch (err) {
        ctx.status = 200;
        ctx.body = httpResult.fail(null, null, err.message || '服务器出现未知错误');
    }
}





//创建一个token
const createToken = (param) => {
    let token = jwt.sign(param, app.TOKEN.TOKEN_KEY, {
        expiresIn: app.TOKEN.TOKEN_TIME
    })
    return token
}
//验证token 
const verifyToken = (token) => {
    let verify = jwt.verify(token, app.TOKEN.TOKEN_KEY, (error, decoded) => {
        if (error) {
            return false;
        }
        return decoded;
    });
    return verify;
};



/**
 * @Author: hzj-1510017964@qq.com
 * @route: POST GET info
 * @desc: info
 * @info: 请求拦截器
 */


//拦截器
const interceptor = async (ctx, next) => {
    let URL = ctx.request.url
    let noneInterceptorURL = app.TOKEN.NO_INTERCEPTOR_ROUTES
    let type = noneInterceptorURL.indexOf(URL)     //-1 不存在---要拦截截验证   !=-1存在----不拦截
    if (type == -1) {
        let token = ctx.request.header[app.TOKEN.TOKEN_HEADER_NAME]  //获取header的token  
        if (!token) {
            ctx.body = httpResult.fail(null, null, 'token为空');
        }
        let token_state = verifyToken(token)

        if (token_state) {
            await redisDb.get(app.TOKEN.TOKEN_IN_REDIS_DBNAME, app.REDIS.APP_REDIS_NAME + token_state[app.REDIS.APP_REDIS_SIGN]).then(res => {
                console.log(`redis上传的token___${res}`)
                console.log(`user上传的token___${token}`)
                if (token == res) {
                    ctx.token_state = token_state
                } else {
                    ctx.body = httpResult.fail(null, null, 'token无效');
                }
            }).catch(err => {
                ctx.body = httpResult.fail(null, null, 'token无效');
                
            })
        } else {
            ctx.body = httpResult.fail(null, null, 'token无效');
        }
    }
    await next()
}


module.exports = {
    createToken,
    verifyToken,
    interceptor,
    errorSystem
}